<?php
/**
 * 自我更新控制器
 */
namespace app\chaochao\controller;

class Update extends Common
{
	/**
	 * 配置列表
	 * @author 秋水
	 * @DateTime 2019-03-24T18:01:57+0800
	 */
	public function file()
	{
		return $this->fetch();
	}

	/**
	 * 获取配置列表信息
	 * @author 秋水
	 * @DateTime 2019-03-24T18:03:02+0800
	 */
	public function fileList()
	{
		$page = input('page', 1);
		$limit = input('limit', 15);
		$where = [];
        $list = model('UpdateFile')->where($where)->page($page, $limit)->order('id asc')->select()->toArray();
        $count = model('UpdateFile')->where($where)->count();

        return json(['code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $list]);
	}

	/**
	 * 添加配置
	 * @author 秋水
	 * @DateTime 2019-03-24T18:15:40+0800
	 */
	public function addFile()
	{
		if(request()->isPost()) {
			$host = input('host', '');
			$path = input('path', '');
			$port = input('port', '');
			$version = input('version', '');
			$md5 = input('md5', '');
			$key = input('key', '');
			$status = input('status', 0);

			$addData = [
				'host' => $host,
				'path' => $path,
				'port' => $port,
				'version' => $version,
				'md5' => $md5,
				'key' => $key,
				'status' => $status,
			];

			if($status == 1) {
				// 如果配置信息为“启用”状态，则关闭其他已启用的配置
				model('UpdateFile')->where([['status','eq',1]])->update(['status'=>0]);
			}

			$r = model('UpdateFile')->insert($addData);
			if($r) {
				return json(['code'=>0, 'msg'=>'添加成功']);
			} else {
				return json(['code'=>40001, 'msg'=>'添加失败']);
			}
		} else {
			return $this->fetch();
		}
	}

	/**
	 * 添加配置
	 * @author 秋水
	 * @DateTime 2019-03-24T18:15:40+0800
	 */
	public function editFile()
	{
		if(request()->isPost()) {
			$id = input('id', 0);
			$host = input('host', '');
			$path = input('path', '');
			$port = input('port', '');
			$version = input('version', '');
			$md5 = input('md5', '');
			$key = input('key', '');
			$status = input('status', 0);

			$updateData = [
				'host' => $host,
				'path' => $path,
				'port' => $port,
				'version' => $version,
				'md5' => $md5,
				'key' => $key,
				'status' => $status,
			];

			if($status == 1) {
				// 如果配置信息为“启用”状态，则关闭其他已启用的配置
				model('UpdateFile')->where([['status','eq',1]])->update(['status'=>0]);
			}

			$r = model('UpdateFile')->where([['id','eq',$id]])->update($updateData);
			if($r !== false) {
				return json(['code'=>0, 'msg'=>'编辑成功']);
			} else {
				return json(['code'=>40001, 'msg'=>'编辑失败']);
			}
		} else {
			$id = input('id', 0);
			$data = model('UpdateFile')->where([['id','eq',$id]])->find();

			$this->assign('data', $data);
			return $this->fetch();
		}
	}

	/**
	 * 删除配置文件
	 * @author 秋水
	 * @DateTime 2019-03-24T18:36:06+0800
	 * @return   [type]                   [description]
	 */
	public function delFile()
	{
		$id = input('id', 0);
		$where = [['id','eq',$id]];

		$r = model('UpdateFile')->where($where)->delete();

		if($r) {
			return json(['code'=>0,'msg'=>'删除成功']);
		} else {
			return json(['code'=>40001,'msg'=>'删除失败']);
		}
	}
}